package com.cmbchina.service;

import com.cmbchina.entity.BaiduExchangeRate;
import com.cmbchina.entity.Currency;
import com.cmbchina.entity.ExchangeRate;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 汇率服务
 *  从百度网站获取汇率
 */
public class BaiduExchangeRateService implements ExchangeRateService{

    @Override
    public ExchangeRate getRate(Currency from, Currency to) {
        //1、从百度网站获取新浪格式汇率
        BaiduExchangeRate sinaRate = getBaiduExchangeRate(from, to);
        //2、将百度汇率格式转换为当前系统的汇率格式
        ExchangeRate rate = convertExhangeRate(sinaRate);
        return rate;
    }

    /**
     * 将百度汇率格式转换当前汇率格式
     * @param baiduRate
     * @return
     */
    private ExchangeRate convertExhangeRate(BaiduExchangeRate baiduRate){
        if(Objects.isNull(baiduRate)){
            throw new IllegalArgumentException("汇率不能为null");
        }
        Currency sourceCurrency = baiduRate.getSourceCurrency();
        Currency targetCurrency = baiduRate.getTargetCurrency();
        //格式转换
        BigDecimal rate = baiduRate.getRateNum();
        return new ExchangeRate(rate, sourceCurrency, targetCurrency);
    }

    /**
     * 从百度网站获取汇率
     * @param from
     * @param to
     * @return
     */
    private BaiduExchangeRate getBaiduExchangeRate(Currency from, Currency to){
        //模拟从百度网站获取汇率
        return new BaiduExchangeRate(new BigDecimal("1.5"), from, to);
    }
}
